const {
  $Message
} = require('/component/iView/base/index');
const mtjwxsdk = require('./utils/mtj-wx-sdk.js');
// http://www.shareketang.com:8080/swagger-ui/index.html#/  "http://1.117.75.111:8080/"
App({
  globalData: {
    baseAPI: "https://shareketang.com",
    hadInfo: false,
    code_can_use: false,
    banji_info: {
      "courseName": null,
      "className": null,
      "teacher_id": null,
      "teacherId": null,
    },    //修改了空值，之前只是null
    teacher_info: {
      "account": null,
      "createTime": null,
      "gender": null,
      "id": null,
      "name": null,
      "password": null,
      "permission": null
    },
    student_info: {
      "account": null,
      "createTime": null,
      "gender": null,
      "id": null,
      "name": null,
      "password": null,
      "permission": null
    },
    chat_info: {
      'sender_id':null,
      'receiver_id':null,
      'sender_identity':null,
      'receiver_identity':null
    },
    pageSize: 20
  },

  getLogin: function () {
    let _this = this
    return new Promise(function (resolve, reject) {
      let data = {}
      // 查看是否有登录myCode字段
      let myCode = wx.getStorageSync('myCode')

      if (null != myCode && myCode != '') {
        // 登录

        // 如果有myCode就检查是否过期
        if (_this.globalData.code_can_use == false && (null != myCode && myCode != '')) {
          let url = ''
          if (wx.getStorageSync('people') == 'student') {
            url = '/student_code_is_f?'
            data = {
              'code': myCode,
              'student_account': wx.getStorageSync('account')
            }
          } else if (wx.getStorageSync('people') == 'teacher') {
            url = '/teacher_code_is_f?'
            data = {
              'code': myCode,
              'teacher_account': wx.getStorageSync('account')
            }
          }
          _this.formPost(url, data).then(res => {
            // console.log('re',res);
            if (res['message'] == "未过期") {
              _this.globalData.code_can_use = true
              console.log('formPost检查code:未过期');
              resolve()
            } else {
              console.log('formPost检查code:已过期');
              wx.setStorageSync('myCode', null)
              wx.navigateTo({
                url: '/pages/user/bind/index',
              })
            }
          })
        }

        // 如果有myCode且未获得数据就getInfo
        if (_this.globalData.hadInfo == false && (null != myCode && myCode != '')) {
          let gerInfo_url = ''
          if (wx.getStorageSync("people") == 'teacher') {
            gerInfo_url = '/get_teacher_detail?account='
          } else if (wx.getStorageSync("people") == 'student') {
            gerInfo_url = '/get_student_detail?account='
          }
          _this.formGet(gerInfo_url + wx.getStorageSync("account") + '&code=' + wx.getStorageSync("myCode")).then(res => {
            console.log('formGet setInfo设置用户全局信息:', res);
            let data = res
            _this.setInfo(data)
            _this.globalData.hadInfo = true
          })
        }


      } else if (null == myCode || myCode == '') {
        // 如果没有myCode就跳转登录页面
        wx.navigateTo({
          url: '/pages/user/bind/index',
        })
      }

    })
  },

  onLaunch: function () {
    this.getLogin()
    .then(() => {
      console.log('登录成功');
    })
    .catch((err) => {
      console.error('登录失败', err);
    });   //增加登录提示
  },

  message: function (content, type) {
    $Message({
      content: content,
      type: type
    });
  },

  formPost: function (url, data) {
    let _this = this
    return new Promise(function (resolve, reject) {
      console.log('#############')
      console.log('formPostdata', data)
      data['code'] = wx.getStorageSync('myCode')
      wx.showNavigationBarLoading();
     
      wx.request({
        url: _this.globalData.baseAPI + url,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'code': wx.getStorageSync('myCode')
        },
        method: 'POST',
        data,
        success(res) {
          console.log('formPost success res:', res);
          if (res.statusCode == 200) {
            resolve(res.data)
            return true;
          } else if (res.statusCode !== 200) {
            reject('res.statusCode：' + String(res.statusCode) + '自定义出错(app.js formPost):' + String(res.data))
            return false;
          }
        },
        fail(res) {
          reject(res.errMsg)
          return false;
        },
        complete(res) {
          wx.hideNavigationBarLoading();
        }
      })
    })
  },

  formGet: function (url) {
    console.log('#############')
    let _this = this
    return new Promise(function (resolve, reject) {
      wx.showNavigationBarLoading();
      wx.request({
        url: _this.globalData.baseAPI + url,
        method: 'GET',
        success(res) {
          console.log('formGet success res:', res);
          if (res.statusCode == 200) {
            resolve(res.data)
            return true;
          } else if (res.statusCode !== 200) {
            reject('res.statusCode：' + String(res.statusCode) + '自定义出错(app.js formGet):' + String(res.data))
            return false;
          }
        },
        fail(res) {
          reject(res.errMsg)
          return false;
        },
        complete(res) {
          wx.hideNavigationBarLoading();
        }
      })
    })
  },

  setInfo: function (data) {
    let _this = this
    if (wx.getStorageSync("people") == 'teacher') {
      _this.globalData.teacher_info['account'] = data['account']
      _this.globalData.teacher_info['createTime'] = data['createTime']
      _this.globalData.teacher_info['gender'] = data['gender']
      _this.globalData.teacher_info['id'] = data['id']
      _this.globalData.teacher_info['name'] = data['name']
      _this.globalData.chat_info['sender_identity'] = 1
      _this.globalData.chat_info['sender_id'] = data['id']
    } else if (wx.getStorageSync("people") == 'student') {
      _this.globalData.student_info['account'] = data['account']
      _this.globalData.student_info['createTime'] = data['createTime']
      _this.globalData.student_info['gender'] = data['gender']
      _this.globalData.student_info['id'] = data['id']
      _this.globalData.student_info['name'] = data['name']
      _this.globalData.chat_info['sender_identity'] = 0
      _this.globalData.chat_info['sender_id'] = data['id']
    }
  }
})